import { login, getInfo } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { constantRoutes } from '@/router'
const state = {
  token: getToken() || null,
  userInfo: {},
  routes: constantRoutes
}

const mutations = {
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  }
}

const actions = {
  logout(context) {
    context.commit('removeToken')
    context.commit('setUserInfo', {})
  },
  async getUserInfo(context) {
    const res = await getInfo()
    // console.log(res)
    context.commit('setUserInfo', res)
    return res
  },
  async Login(context, reqData) {
    const res = await login(reqData)
    context.commit('setToken', res)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

